import random
from network_manager import NetworkManager
from web_ui import WebUIManager
from file_uploader import FileUploader
from recordvoice import Recorder,i2s_config
import ujson
import time
from oledprint import getI2Cstatue,threaded_print,OLEDPrinter
w=getI2Cstatue()
if w :
    oled_printer = OLEDPrinter(w)  
    global print  # 声明 print 为全局变量
    def print(*args, **kwargs):
        threaded_print(oled_printer,*args, **kwargs)
config_file = "config.json"    
network_manager = NetworkManager()
web_ui = WebUIManager(config_file,network_manager)
recorder = Recorder(i2s_config=i2s_config, button_pin=18, led_pin=2)
file_uploader = FileUploader()
def generate_random_string(length=7):
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    return ''.join(random.choice(charset) for _ in range(length))


def do_connect():
    try:
        with open(config_file, 'r') as f:
            config = ujson.load(f)
            ssid = config.get('ssid', '')
            password = config.get('password', '')
        if ssid and password:
            network_manager.connect_wifi(ssid, password)

        else:
            raise Exception("no saved ssid & password ")
    except Exception as e:
        network_manager.start_ap()
        web_ui.start_web_server()



if __name__ == "__main__":

    do_connect()
    
    while True:
        if recorder.exit_program:
            recorder = Recorder(i2s_config=i2s_config, button_pin=18, led_pin=2)
        # 运行录音器
        recorder.run()

        # 录音完成后，等待一段时间再尝试上传文件
        time.sleep_ms(300)  # 300 毫秒
        try:

            with open(config_file, 'r') as f:
                config = ujson.load(f)
                upload_url = config.get('upload_url', '')
            random_name = generate_random_string() + "-audio.wav"
            file_uploader.upload_file("audio.wav", random_name, upload_url)

        except Exception as e:
            print (e)
            network_manager.start_ap()
            web_ui.start_web_server()   
